package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务表 服务实现类
 * </p>
 *
 * @author lwf
 * @since 2025-09-15
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Autowired
    private ServeItemMapper serveItemMapper;
    @Autowired
    private RegionMapper regionMapper;

    /**
     * 根据区域id查询区域服务列表
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryListByRegionId(servePageQueryReqDTO.getRegionId()));
    }

    /**
     * 添加区域服务
     * @param serveUpsertReqDTOList
     */
    @Override
    @Transactional
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        for(ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOList){
            //1.校验服务是否为启用状态
            ServeItem serveItem = serveItemMapper.selectById(serveUpsertReqDTO.getServeItemId());
            if(ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()){
                throw new ForbiddenOperationException("该服务未启用无法添加到区域下使用");
            }
            //2.检验是否重复新增
            Long count = lambdaQuery()
                    .eq(Serve::getRegionId,serveUpsertReqDTO.getRegionId())
                    .eq(Serve::getServeItemId,serveUpsertReqDTO.getServeItemId())
                    .count();
            if(count > 0){
                throw new ForbiddenOperationException(serveItem.getName() + "服务已经存在");
            }
            //3.新增服务
            Serve serve = BeanUtil.toBean(serveUpsertReqDTO,Serve.class);
            serve.setPrice(serveItem.getReferencePrice());
            Region region = regionMapper.selectById(serveUpsertReqDTO.getRegionId());
            serve.setCityCode(region.getCityCode());
            baseMapper.insert(serve);
        }
    }

    /**
     * 根据区域id修改价钱
     * @param id
     * @param price
     */
    @Override
    @Transactional
    public Serve update(Long id, BigDecimal price) {
        //更新价格
        Boolean update = lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getPrice,price)
                .update();
        if(!update){
            throw new CommonException("修改价格失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * 上架服务
     * @param id
     * @return
     */
    @Override
    @Transactional
    @CachePut(value=RedisConstants.CacheName.SERVE,key = "#id",cacheManager =
    RedisConstants.CacheManager.ONE_DAY)
    public Serve onSale(Long id) {
        //校验
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        Integer saleStatus = serve.getSaleStatus();
        if(!(saleStatus==FoundationStatusEnum.INIT.getStatus() || saleStatus==FoundationStatusEnum.DISABLE.getStatus())){
            throw new ForbiddenOperationException("草稿或者下架状态方可上架");
        }
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        Integer activeStatus = serveItem.getActiveStatus();
        if(!(FoundationStatusEnum.ENABLE.getStatus()==activeStatus)){
            throw new ForbiddenOperationException("服务项为启用状态可以上架");
        }
        //上架
        Boolean update = lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getSaleStatus,FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if(!update){
            throw new CommonException("启动服务失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * 删除区域服务
     * @param id
     * @return
     */
    @Override
    @Transactional
    public void deleteById(Long id) {
        //查询服务类型
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("服务类型不存在");
        }
        //草稿状态方可删除
        Integer saleStatus = serve.getSaleStatus();
        if(!(saleStatus==FoundationStatusEnum.INIT.getStatus())){
            throw new ForbiddenOperationException("草稿状态方可删除");
        }
        baseMapper.deleteById(id);
    }

    /**
     * 服务下架
     * @param id
     */
    @Override
    @Transactional
    @CacheEvict(value = RedisConstants.CacheName.SERVE, key = "#id")
    public Serve offSale(Long id) {
        //校验
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        Integer saleStatus = serve.getSaleStatus();
        if(!(saleStatus==FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("上架状态方可下架");
        }
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        Integer activeStatus = serveItem.getActiveStatus();
        if(!(FoundationStatusEnum.ENABLE.getStatus()==activeStatus)){
            throw new ForbiddenOperationException("服务项为启用状态可以下架");
        }
        //上架
        Boolean update = lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getSaleStatus,FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if(!update){
            throw new CommonException("启动服务失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * 设置热门服务开发
     * @param id
     */
    @Override
    @Transactional
    public Serve onHot(Long id) {
        //校验
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        Integer saleStatus = serve.getSaleStatus();
        if(!(saleStatus==FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("上架状态才可设置热门");
        }
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        Integer activeStatus = serveItem.getActiveStatus();
        if(!(FoundationStatusEnum.ENABLE.getStatus()==activeStatus)){
            throw new ForbiddenOperationException("服务项为启用状态可以设置热门");
        }
        //设置热门
        Boolean update = lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getIsHot,FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if(!update){
            throw new CommonException("启动服务失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * 取消热门服务开发
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Serve offHot(Long id) {
        //校验
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        Integer saleStatus = serve.getSaleStatus();
        if(!(saleStatus==FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("上架状态才可取消热门");
        }
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        Integer activeStatus = serveItem.getActiveStatus();
        if(!(FoundationStatusEnum.ENABLE.getStatus()==activeStatus)){
            throw new ForbiddenOperationException("服务项为启用状态可以取消热门");
        }
        //设置热门
        Boolean update = lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getIsHot,FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if(!update){
            throw new CommonException("启动服务失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * 查询上架服务
     * @param id
     * @param status
     * @return
     */
    @Override
    public int queryServeCountByRegionIdAndSaleStatus(Long id, int status) {
        int count = Math.toIntExact(lambdaQuery()
                .eq(Serve::getRegionId, id)
                .eq(Serve::getSaleStatus, status)
                .count());
        return count;
    }

    /**
     * 查询区域服务信息并进行缓存
     * @param id 对应serve表的主键
     * @return
     */
    @Override
    @Cacheable(value = RedisConstants.CacheName.SERVE,key = "#id")
    public Serve queryServeByIdCache(Long id) {
        return getById(id);
    }
}
